<template>
  <div class="address-cascader">
    <el-cascader
      ref="cascader"
      popper-class="address-cascader__popper"
      :separator="separator"
      v-bind="$attrs"
      v-model="innerValue"
      :options="cityOptions"
      :props="cascaderProps"
      @change="changeHandle"
      placeholder="请选择地区"
      clearable
    >
    </el-cascader>
  </div>
</template>

<script>
import { getProvince, getCity, getDistrict } from '@/api/common'
import { isString } from 'lodash'
export default {
  name: 'hycAddressCascader',
  props: {
    insertResetZoom: {
      type: Boolean,
      default: false,
    },
    showLabel: {
      type: Boolean,
      default: false,
    },
    value: {
      type: Object,
    },
    level: {
      type: Number,
      default: 2,
    },
    isPlaceholder: {
      type: Boolean,
      default: true,
    },
    expandTrigger: {
      type: String,
      default: 'hover',
    },
    /**
     * value 传出的字段组
     */
    valueKey: {
      type: String,
      default: 'value',
    },
    separator: {
      type: String,
      default: '—',
    },
    checkStrictly: {
      default: true,
    },
  },
  data() {
    return {
      refreshkey: 1,
      cityOptions: [],
      innerValue: [],
      isLazy: true,
      firstFlag: true,
    }
  },
  computed: {
    cascaderProps() {
      return {
        expandTrigger: this.expandTrigger,
        checkStrictly: this.checkStrictly,
        value: this.valueKey,
        lazy: true,
        lazyLoad: async (node, resolve) => {
          const { data, level } = node
          let nodes = []
          if (level === 0) {
            this.firstNode = node
            this.firstResolve = resolve
            nodes = await this.getAddress(level)
            // if (this.insertResetZoom) {
            //   nodes.unshift({
            //     label: '全国',
            //     leaf: true,
            //     value: '-1,全国',
            //   })
            // }
          } else if (level <= this.level) {
            nodes = await this.getAddress(level, data.value)
          }
          nodes.forEach((item) => {
            item.leaf = level >= this.level
          })
          // 通过调用resolve将子节点数据返回，通知组件数据加载完成
          resolve(nodes)
        },
      }
    },
  },
  watch: {
    value: {
      handler(val, oldVal) {
        if (val && val != oldVal) {
          this.innerValue = []
          if (val.province) {
            this.innerValue.push(val.province)
          }

          if (val.city) {
            this.innerValue.push(val.city)
          }

          if (val.district) {
            this.innerValue.push(val.district)
          }
          if (
            this.innerValue.length &&
            this.firstFlag &&
            this.firstNode &&
            this.firstResolve
          ) {
            this.firstFlag = false
            this.cascaderProps.lazyLoad(this.firstNode, this.firstResolve)
          }
        }
      },
      immediate: true,
    },
  },
  methods: {
    async getAddress(flag, areaId = 0) {
      const getAddressList = [getProvince, getCity, getDistrict]
      if (isString(areaId)) {
        areaId = areaId.split(',')[0] || 0
      }
      const params = flag === 0 ? {} : { parent: areaId }
      let result = []
      try {
        const data = await getAddressList[flag](params)
        result = (data || []).map((item) => ({
          label: item.name,
          // 值的id
          // value: !this.showLabel ? item.id : item.id + ',' + item.name,
          value: !this.showLabel
            ? item.id
            : item.id + ',' + item.name + ',' + item.code,
        }))
        // if (flag !== 0 && this.isPlaceholder) {
        //   result.unshift({
        //     label: '--请选择--',

        //     value: '',
        //   })
        // }
      } catch (error) {
        console.error(error)
      }
      return result
    },
    clearHandle() {
      this.innerValue = []
      this.$emit('input', {})
    },
    changeHandle(val) {
      this.$refs.cascader.toggleDropDownVisible(false)
      this.firstFlag = false
      const map = ['province', 'city', 'district']
      let list = {}
      val &&
        val.forEach((item, index) => {
          list[map[index]] = item
        })

      this.$emit('input', list)
    },
  },
}
</script>

<style lang="scss">
.address-cascader {
  .el-cascader {
    width: 100%;
  }
}
.address-cascader__popper {
  .el-cascader-panel {
    height: 204px;
    overflow-y: auto;
  }
  .el-scrollbar__wrap {
    overflow-x: hidden;
    margin-right: 0 !important;
  }
}
.the-city-cascader {
  width: 100%;
  .city-cascader {
    width: 100%;
  }
}
</style>
